<script setup lang="ts">
import { useUserStore } from "~/store/useUser";
import { getRegisterCode, sendSmsCodeAPI, verifySmsCode } from "~/api/user";

const formData = ref({});

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(["close", "confirm"]);
const close = () => {
  emits("close");
};
const userStore = useUserStore();

// 获取手机号：优先使用 props，其次使用 store
const getPhoneNumber = () => {
  return props.userInfo?.phonenumber || userStore.getUserInfo?.phonenumber || "";
};

const confirm = async () => {
  if (!isSend.value) return ElMessage.warning("请先获取验证码");
  // 校验验证码是不是4位数字
  if (!/^\d{4}$/.test(formData.value.code)) {
    return ElMessage.warning("请输入正确的验证码");
  }
  
  // 调用接口验证验证码
  try {
    const phoneNumber = getPhoneNumber();
    if (!phoneNumber) {
      return ElMessage.warning("请先绑定手机号");
    }
    
    // 调用验证接口验证验证码
    const verifyResult = await verifySmsCode({
      phone: phoneNumber,
      smsCode: formData.value.code
    });
    
    // 根据接口说明：code === 200 且 data === true 表示验证成功
    if (verifyResult.code === 200 && verifyResult.data === true) {
      // 验证成功，通知父组件
      emits("confirm", formData.value.code);
    } else if (verifyResult.code === 200 && verifyResult.data === false) {
      // 验证码错误
      ElMessage.error("验证码错误，请重新输入");
    } else {
      // 验证码过期或其他错误
      ElMessage.error(verifyResult.msg || "验证码验证失败，请重试");
    }
  } catch (error) {
    console.error('验证验证码失败:', error);
    ElMessage.error("验证码验证失败，请重试");
  }
};
// 获取验证码
const getStatus = ref(false);
const isSend = ref(false);
const time = ref(60);
const timer = ref();
const getSmsCodeHandle = async () => {
  const phoneNumber = getPhoneNumber();
  if (!phoneNumber) {
    return ElMessage.warning("请先绑定手机号");
  }
  try {
    if (getStatus.value || time.value !== 60) return;
    getStatus.value = true;
    // 使用新的短信接口
    const data = await sendSmsCodeAPI(phoneNumber);
    if (data.code === 200) {
      ElMessage.success("发送成功");
      isSend.value = true;
      timer.value = setInterval(() => {
        time.value--;
        if (time.value === 0) {
          getStatus.value = false;
          time.value = 60;
          clearInterval(timer.value);
        }
      }, 1000);
    }
  } catch (e) {
    console.log(e);
    getStatus.value = false;
    time.value = 60;
    if (timer.value) clearInterval(timer.value);
  }
};
const rules = ref({
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!/^\d{4}$/.test(value)) {
          callback(new Error("请输入正确的验证码"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});
</script>

<template>
  <div class="dialog" @click="close">
    <div class="dialog-box" @click.stop>
      <div class="header">
        <div class="left">
          <img src="~/assets/dialog-icon.png" alt="" />
          <span>请验证你的手机号</span>
        </div>
        <img class="close" src="~/assets/modal-close.png" alt="" @click="close" />
      </div>
      <div class="dialog-content">
        <el-form
          :model="formData"
          label-position="top"
          :rules="rules"
          :hide-required-asterisk="true"
        >
          <el-form-item label=" " prop="code">
            <p class="tips">将向{{ getPhoneNumber() || '您的手机号' }}发送验证码</p>
            <el-input
              v-model="formData.code"
              placeholder="请输入验证码"
              style="height: 40px"
              maxlength="4"
              :validate-event="true"
            >
              <template #append>
                <span
                  style="color: rgba(29, 191, 115, 1); cursor: pointer"
                  @click="getSmsCodeHandle"
                  >{{ getStatus ? `${time}S` : "获取验证码" }}</span
                >
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="footer">
        <span class="btn" @click="close">取消</span>
        <span class="btn" @click="confirm">确认</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(25, 30, 40, 0.4);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-box {
  width: 400px;
  background: #ffffff;
  border-radius: 12px 12px 12px 12px;
  padding: 24px;

  .header {
    display: flex;
    align-items: center;
    padding-bottom: 20px;

    .left {
      flex: 1;
      display: flex;
      align-items: center;

      img {
        width: 20px;
        height: 20px;
        margin-right: 4px;
      }

      span {
        font-size: 16px;
        color: #191e28;
        font-weight: bold;
      }
    }

    .close {
      width: 18px;
      height: 18px;
      cursor: pointer;
    }
  }
  .footer {
    display: flex;
    padding: 32px 0 0;
    justify-content: flex-end;
    span {
      width: 92px;
      height: 36px;
      cursor: pointer;
    }
    .btn:nth-child(1) {
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid rgba(25, 30, 40, 0.08);
      display: flex;
      align-items: center;
      justify-content: center;
      color: rgba(25, 30, 40, 0.6);
      margin-right: 12px;
    }
    .btn:nth-child(2) {
      background: #1dbf73;
      border-radius: 8px 8px 8px 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
    }
  }
  .dialog-content p {
    display: flex;
  }
  .textarea {
    margin-top: 10px;
    textarea {
      width: 100%;
      height: 96px;
      background: rgba(25, 30, 40, 0.02);
      border-radius: 12px 12px 12px 12px;
      border: 1px solid rgba(25, 30, 40, 0.08);
      padding: 16px;
      box-sizing: border-box;
      resize: none;
    }
  }
}
</style>

<style>
.dialog .el-select__wrapper {
  height: 40px;
}
.dialog .el-form--default.el-form--label-top .el-form-item .el-form-item__label {
  color: #191e28;
  font-weight: bold;
}
.tips {
  color: rgba(25, 30, 40, 0.48);
}
</style>
